<?php

// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2030 http://www.jmzh1688.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: lxl
// +----------------------------------------------------------------------

/*
待执行任务
1.  文章的 支持双标签，用于汉藏双语编辑

2.  添加编辑 ，支持分类 选择关联

https://snrms.nresoft.com/?m=index&c=index&a=init#basedata/sample/init/categoryid=1/%E6%A0%B7%E5%93%81
3. ERP系统，字典+订单管理 ，订单管理 支持添加修改中多标签，字典选择， 列表关联，及附件上传。全部不可视状态，简单。

4.提示语 代表可能是CRM中的 查找 或添加 表关联

5.很多个添加，很多个列表  order2 采用数组方式

*/

namespace app\comm\controller;

use think\Controller;
use think\Db;
use think\Cache;

use app\admin\model\SysconfigModel;

class Wxpay extends  Controller
{
    /**
     * 公众号支付
     */
    public function _initialize()
    {
        $this->config_name= input("get.config_name");
        $this->data = $this->get_cache( $this->config_name);
        $this->appid =  $this->data['appid'];
        $this->appsecret =  $this->data['appsecret'];
        $this->mch_id =  $this->data['mch_id'];
        $this->notifyurl =  $this->data['notifyurl'];
        $this->key=  $this->data['key'];
        
    }

    public function pay()
    {

        $orderid= input("post.orderid");//$_COOKIE["wx_openid"];//"test".date("YmdHis");
        $openid=  input("post.openid");//$_COOKIE["wx_openid"];
        $title=  input("post.title");//"测试商品";
        $price=  input("post.price");//"测试商品";

        $successurl=  input("post.successurl");
        $failurl=  input("post.failurl");
        
        
     
        $ret = $this->unifiedorder($openid,$orderid,$title,$price);
        if($ret['result_code']=='FAIL'){
            die($ret['err_code_des']);
        }

        $params = [
            'appId'=>$this->appid,
            'timeStamp' =>strval(time()),
            'nonceStr' => md5(time()),
            'package' =>'prepay_id=' . $ret['prepay_id'],
            'signType' =>'MD5',
        ];
        $params['paySign'] = $this->getSign($params);
        $params['openid'] =$openid;
        
        $pay_str = json_encode($params);
      



        $this->assign('successurl',$successurl);
        $this->assign('failurl',$failurl);
        $this->assign('json',$pay_str);
        $this->assign('order_id',$orderid);
        return $this->fetch();

    }

    public function payjson()
    {

        $orderid= input("post.orderid");//$_COOKIE["wx_openid"];//"test".date("YmdHis");
        $openid=  input("post.openid");//$_COOKIE["wx_openid"];
        $title=  input("post.title");//"测试商品";
        $price=  input("post.price");//"测试商品";

     
     
        $ret = $this->unifiedorder($openid,$orderid,$title,$price);


      //  writehtmlfile("/www/wwwroot/wx.jmzh8188.com/runtime/log/202003/log.txt",json_encode($ret));

       // writehtmlfile("/www/wwwroot/wx.jmzh8188.com/runtime/log/202003/log.txt",json_encode($ret));

        if($ret['return_code']=='FAIL'){
            die($ret['err_code_des']);
        }

        $params = [
            'appId'=>$this->appid,
            'timeStamp' =>strval(time()),
            'nonceStr' => md5(time()),
            'package' =>'prepay_id=' . $ret['prepay_id'],
            'signType' =>'MD5',
        ];
        $params['paySign'] = $this->getSign($params);
        $params['openid'] =$openid;
        
        $pay_str = json_encode($params);
      

        $a['json'] =  $pay_str;
        $a['orderid'] =$orderid;

        $str = json_encode($a);
    
        return $str;

    }

    public  function unifiedorder($openid,$ordersn,$title,$price)
    {
        $params = [
            'appid'=> $this->appid,
            'mch_id'=> $this->mch_id,
            'nonce_str'=>md5(time()),
            'body'=>$title,
            'out_trade_no'=>$ordersn,
            'total_fee'=> $price,
            'spbill_create_ip'=>request()->ip(),
            'notify_url'=> $this->notifyurl,
            'trade_type'=>'JSAPI',
            'openid'    => $openid
        ];
        $params['sign'] =$this->getSign($params);
        $xmldata = $this->arr2xml($params);
        $this->logs($xmldata);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $retdata = curlRequest($url,$xmldata);
        $this->logs($retdata);
        $retdata = xml2arr($retdata);
        return $retdata;

    }


    
    /**
     * 微信支付回调处理
    */
    public function notifyUrl(){
        $xml = file_get_contents('php://input');
        $this->logs($xml);
        $data = xml2arr($xml);
        //检查sign
        if($data['sign']!=$this->getSign($data)){
            $this->logs('sign不对');
            return ;
        }

        if($data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS'){
            $arr = [
                'out_trade_no' =>$data['out_trade_no'],
                'pay_type' =>'1',
                'total_amount' =>sprintf("%.2f", $data['total_fee']/100),
                'trade_no' =>$data['transaction_id']
            ];
            /*
            $order = new Order();
            if(!$order->produceOrder($arr)){
                $this->logs("更新订单{$arr['out_trade_no']}失败");
                return ;
            }
            */
            $returnParams = [
                'return_code' => 'SUCCESS',
                'return_msg'  => 'OK'
            ];
            echo arr2xml($returnParams);
        }
    }



    //notifyurl 记录日志
    private function logs($content){
        file_put_contents("./logs/".date("Y-m-d")."_logs.txt", $content."\r\n",FILE_APPEND);
    }

     //数组转xml
 function arr2xml($arr)
 {
         if(!is_array($arr) || count($arr) == 0) return '';

         $xml = "<xml>";
         foreach ($arr as $key=>$val)
         {
                 if (is_numeric($val)){
                         $xml.="<".$key.">".$val."</".$key.">";
                 }else{
                         $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
                 }
         }
         $xml.="</xml>";
         return $xml; 
 }

    private function getSign($arr){
        $arr = array_filter($arr);
        if(isset($arr['sign'])){
            unset($arr['sign']);
        }
        ksort($arr);
        $stringA = urldecode(http_build_query($arr));
        $stringSignTemp = $stringA.'&key='.$this->key;

        $sign = strtoupper(md5($stringSignTemp));
        return $sign;

    }


    
        /**
     * 获取微信配置
     */
    private function get_cache($config_name){
        $wxpay =  Cache::get("wx".$config_name);
        if(empty($wxpay)||true){

            $configmodel = new SysconfigModel();
            $myconfig= $configmodel->getByName($config_name);
             if( $myconfig==null){ 
                 exit("请配置微信公众号登录".$config_name."未配置");
             }
             $wxpay = $myconfig["value"];

             Cache::set("wx".$config_name,$wxpay,60);
        }
        return json_decode($wxpay,true);
    }

}
